<?php
namespace App\Http\Controllers\Manage\Lottery;

use App\Http\Controllers\Manage\CommonController;
use App\Model\Category;
use App\Model\Goods;

class CategoryController extends CommonController
{
    /**
     * 查看分类
     * @return mixed
     */
    public function index()
    {
        $field = [
            'id' => 'ID',
            'name' => '分类名称',
            'keywords' => '关键词',
            'parent_id' => '上级分类',
            'is_show' => '是否显示',
            'show_in_nav' => '在导航中显示'
        ];
        $range = [
            'parent_id' => $this->getCategory(),
            'is_show' => YN(),
            'show_in_nav' => YN()
        ];
        $viewData = [];
        $viewData['title'] = '分类列表';
        # 查询字段
        $viewData['field'] = $field;
        # 列表取值范围替换
        $viewData['range'] = $range;
        # 列表操作菜单
        $viewData['option_title'] = [
            'plus' => [
                'title' => '添加分类',
                'route' => route('manage.lottery.category.resource.create')
            ]
        ];
        # 行操作项的路由
        $viewData['option_row'] = [
            'edit' => [
                'title' => '编辑',
                'route' => 'manage.lottery.category.resource.edit',
            ],

            'trash' => [
                'title' => '删除',
                'route' => 'manage.lottery.category.resource.destroy'
            ]
        ];
        # 模态对话框
        $viewData['option_modal'] = [
            'trash' => [
                'title' => '删除记录',
                'method' => 'DELETE',
                'msg' => '确定要删除分类吗'
            ]
        ];
        # 查询记录
        $category = new Category;
        $viewData['list'] = $this->constraintSelect($category, $field, $range);
        # 渲染视图
        return view('manage.table', $viewData);
    }

    /**
     * 删除分类
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        $count = Goods::where('category_id', $id)->count();
        if ($count > 0) {
            return redirect()->back()->with('error', '该分类下有商品不能删除！');
        }
        $count = Category::where('parent_id', $id)->count();
        if ($count > 0) {
            return redirect()->back()->with('error', '该分类下有子分类不能删除！');
        }
        if (Category::destroy($id)) {
            return redirect()->back()->with('success', '分类删除失败!');
        }
        return redirect()->back()->with('success', '分类删除成功!');
    }

    /**
     * 创建分类页面
     * @return mixed
     */
    public function create()
    {
        $result = Category::get()->toArray();
        $category = treeFormat(tree($result, 'id', 'name', 'parent_id'));
        $category = ['0' => '主分类'] + $category;
        # 表单元素
        $param = [
            'name' => [
                'name' => '分类名称',
                'type' => 'text',
                'col' => '3'
            ],
            'parent_id' => [
                'name' => '上级分类',
                'type' => 'select',
                'col' => '3',
                'range' => $category,
            ],
            'is_show' => [
                'name' => '是否显示',
                'type' => 'select',
                'col' => '3',
                'range' => YN()
            ],
            'show_in_nav' => [
                'name' => '在导航中显示',
                'type' => 'select',
                'col' => '3',
                'range' => YN()
            ],
            'keywords' => [
                'type' => 'text',
                'col' => '12',
                'name' => '关键词',
            ],
            'description' => [
                'name' => '描述',
                'type' => 'textarea',
                'col' => '12',
                'row' => '3'
            ],
        ];

        $viewData = [];
        $viewData['title'] = '添加分类';
        $viewData['form'] = $this->form($param);
        $viewData['form_url'] = route('manage.lottery.category.resource.store');
        $viewData['form_method'] = 'POST';
        $viewData['form_button'] = [
            'return' => [
                'name' => '取消',
                'type' => 'button',
                'route' => route('manage.lottery.category.resource.index')
            ],
            'submit' => [
                'name' => '提交',
                'type' => 'submit',
            ]
        ];
        return view('manage.form', $viewData);

    }

    /**
     * 创建分类操作
     * @return mixed
     */
    public function store()
    {
        if (!$this->request->has('name')) {
            return redirect()->back()->with('error', '请填写分类名称!');
        }
        # 通过父级ID，获取分类的层级
        $parentId = $this->request->input('parent_id');
        $levelArr =  Category::getParentCategory($parentId);
        $level = ($parentId == 0) ? 1 : count($levelArr) + 1;
        # 插入新数据
        $category = new Category();
        $category->name = $this->request->input('name');
        $category->is_show = $this->request->input('is_show');
        $category->keywords = $this->request->input('keywords');
        $category->description = $this->request->input('description');
        $category->parent_id = $parentId;
        $category->level = $level;
        $category->show_in_nav = $this->request->input('show_in_nav');
        $category->create_time = currentTime();
        $category->create_user = $this->user['id'];
        if ($category->save()) {
            return redirect()->route('manage.lottery.category.resource.edit', ['id' => $category->id])->with('success', '分类创建成功!'); # 更新成功后跳转到列表页
        }
        return redirect()->back()->with('error', '分类创建失败!');
    }

    /**
     * 修改分类信息页面
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        # 查询记录数据
        $data = Category::find($id);
        $result = Category::get()->toArray();
        $category = treeFormat(tree($result, 'id', 'name', 'parent_id'));
        $category = ['0' => '主分类'] + $category;
        # 表单元素
        $param = [
            'name' => [
                'name' => '分类名称',
                'type' => 'text',
                'col' => '3',
                'value' => $data->name,
            ],
            'parent_id' => [
                'name' => '上级分类',
                'type' => 'select',
                'col' => '3',
                'range' => $category,
                'value' => $data->parent_id,
            ],
            'is_show' => [
                'name' => '是否显示',
                'type' => 'select',
                'col' => '3',
                'range' => YN(),
                'value' => $data->is_show,
            ],
            'show_in_nav' => [
                'name' => '在导航中显示',
                'type' => 'select',
                'col' => '3',
                'range' => YN(),
                'value' => $data->show_in_nav,
            ],
            'keywords' => [
                'name' => '关键词',
                'type' => 'text',
                'col' => '12',
                'value' => $data->keywords,
            ],
            'description' => [
                'name' => '描述',
                'type' => 'textarea',
                'col' => '12',
                'row' => '3',
                'value' => $data->description,
            ],
        ];

        $viewData = [];
        $viewData['title'] = '查看分类';
        $viewData['nav'] = $this->navTab('category', 'main', ['id'=>$id]);
        $viewData['form'] = $this->form($param);
        $viewData['form_url'] = route('manage.lottery.category.resource.update', ['id' => $id]);
        $viewData['form_method'] = 'PUT';
        $viewData['form_button'] = [
            'return' => [
                'name' => '取消',
                'type' => 'button',
                'route' => route('manage.lottery.category.resource.index')
            ],
            'submit' => [
                'name' => '提交',
                'type' => 'submit',
            ]
        ];
        # 渲染视图
        return view('manage.form', $viewData);
    }

    /**
     * 修改分类信息操作
     * @param $id
     * @return mixed
     */
    public function update($id)
    {
        if (!$this->request->has('name')) {
            return redirect()->back()->with('error', '请填写分类名称!');
        }
        $parentId = $this->request->input('parent_id');
        if ($parentId == $id) {
            return redirect()->back()->with('error', '上级分类不能是自己！');
        }
        # 通过父级ID，获取分类的层级
        $levelArr =  Category::getParentCategory($parentId);
        $level = ($parentId == 0) ? 1 : count($levelArr) + 1;
        # 更新数据
        $category = Category::find($id);
        $category->name = $this->request->input('name');
        $category->is_show = $this->request->input('is_show');
        $category->keywords = $this->request->input('keywords');
        $category->description = $this->request->input('description');
        $category->parent_id = $parentId;
        $category->level= $level;
        $category->show_in_nav = $this->request->input('show_in_nav');
        if ($category->save()) {
            return redirect()->route('manage.lottery.category.resource.index')->with('success', '分类信息修改成功!'); # 更新成功后跳转到列表页
        }
        return redirect()->back()->with('error', '分类信息修改失败');
    }

    /**
     * 获取商品属性列表
     * @return mixed
     */
    private function getCategory()
    {
        $category = array();
        $result = Category::where('is_show', 1)->get();
        foreach ($result as $key => $val) {
            $category[$val->id] = $val->name;
        }
        $category = ['0' => '主分类'] + $category;
        return $category;
    }
}